package com.lastproject.ejb.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

import javax.ejb.Stateless;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.BookDTO;
import com.lastproject.dto.BorrowedDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.BookDAORemote;
import com.lastproject.ejb.dao.BorrowedDAORemote;
import com.lastproject.ejb.dao.UserDAORemote;

/**
 * Session Bean implementation class TimerLibraryBean
 */
@Stateless
public class TimerLibraryBean implements TimerLibraryBeanRemote {

	/**
	 * Default constructor.
	 */
	public TimerLibraryBean() {
		// TODO Auto-generated constructor stub
	}

	@Resource
	TimerService timerService;

	@PersistenceContext
	EntityManager entityManager;

	@EJB
	BorrowedDAORemote borrowedDAORemote;

	@EJB
	UserDAORemote userDAORemote;

	@EJB
	BookDAORemote bookDAORemote;

	@Override
	public void startTimer(Serializable info, int timeInSec) {

		System.out.println(info.toString());
		TimerConfig timerConfig = new TimerConfig();
		timerConfig.setInfo(info);
		timerService.createSingleActionTimer(timeInSec, timerConfig);
	}

	@Timeout
	public void sendEmailLibrary(Timer t) {

		// send message to MDB
		System.out.println("on timeout");
		InitialContext ic;
		ConnectionFactory cf = null;
		Queue destination = null;
		// System.out.println("timerBean. name: " + t.getInfo().toString());

		String infoString = t.getInfo().toString();
		Integer idBorrowed = Integer.parseInt(infoString.substring(infoString
				.indexOf("_") + 1));

		try {
			ic = new InitialContext();
			cf = (ConnectionFactory) ic.lookup("jms/firstFactory");
			destination = (Queue) ic.lookup("jms/firstResource");

		} catch (NamingException e) {
			e.printStackTrace();
		}

		BorrowedDTO borrowedDTO = borrowedDAORemote.findById(idBorrowed);
		BookDTO bookDTO = bookDAORemote.findById(borrowedDTO.getIdBook());
		UserDTO userDTO = userDAORemote.findById(borrowedDTO.getIdUser());

		try (Connection conn = cf.createConnection();
				Session session = conn.createSession(false,
						Session.AUTO_ACKNOWLEDGE);
				MessageProducer producer = session.createProducer(destination)) {
			conn.start();
			Message myMessage = session.createTextMessage();

			myMessage.setStringProperty("userEmail", userDTO.getWorkEmail());
			myMessage.setStringProperty("bookName", bookDTO.getName());

			producer.send(myMessage);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stopTimer(Serializable info) {
		
		Timer timer = null;
		Collection<Timer> timers = timerService.getTimers();
		for (Object object : timers) {
			timer = (Timer) object;
			if (timer.getInfo().equals(info)) {
				timer.cancel();
				break;
			}
		}
		System.out.println("timerLibraryBean.stopTimer " + info.toString());
	}
}
